"use client"

import { useState, useMemo } from "react"
import { useNavigate } from "react-router-dom"
import {
  Row,
  Col,
  Button,
  Input,
  Select,
  Typography,
  Empty,
  Spin,
  Pagination,
  Modal,
  Form,
  Card,
  Tag,
  Space,
  Table,
  List,
  Tooltip,
  Divider,
} from "antd"
import {
  PlusOutlined,
  SearchOutlined,
  FilterOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  TeamOutlined,
  TableOutlined,
  AppstoreOutlined,
  ClockCircleOutlined,
  AppstoreAddOutlined,
} from "@ant-design/icons"
import { useHosts } from "../contexts/HostsContext"
import "../styles/global.scss"
import "./ProjectsView.scss"

const { Title, Text, Paragraph } = Typography
const { Option } = Select
const { confirm } = Modal

const ProjectsView = () => {
  const navigate = useNavigate()
  const { projects, departments, modules, loading, addProject, updateProject, deleteProject } = useHosts()

  const [searchText, setSearchText] = useState("")
  const [selectedDepartment, setSelectedDepartment] = useState<string | undefined>(undefined)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(8)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [isEditModalVisible, setIsEditModalVisible] = useState(false)
  const [editingProject, setEditingProject] = useState<any>(null)
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const [viewMode, setViewMode] = useState<"card" | "table">("card")
  const [showSearchResults, setShowSearchResults] = useState(false)

  // Helper function to highlight matching text
  const highlightText = (text: string, query: string) => {
    if (!query) return text

    const parts = text.split(new RegExp(`(${query})`, "gi"))
    return (
      <>
        {parts.map((part, i) =>
          part.toLowerCase() === query.toLowerCase() ? (
            <span key={i} style={{ backgroundColor: "#ffd666", padding: "0 2px" }}>
              {part}
            </span>
          ) : (
            part
          ),
        )}
      </>
    )
  }

  // Search functionality that includes modules
  const searchResults = useMemo(() => {
    if (!searchText) return []

    const results = []

    // Search in projects
    const matchedProjects = projects.filter(
      (project) =>
        project.name.toLowerCase().includes(searchText.toLowerCase()) ||
        (project.description && project.description.toLowerCase().includes(searchText.toLowerCase())),
    )

    for (const project of matchedProjects) {
      const department = departments.find((d) => d.id === project.departmentId)
      results.push({
        type: "project",
        id: project.id,
        name: project.name,
        department: department?.name || "",
        departmentId: project.departmentId,
        highlight: highlightText(project.name, searchText),
        description: project.description || "",
      })
    }

    // Search in modules
    const matchedModules = modules.filter(
      (module) =>
        module.name.toLowerCase().includes(searchText.toLowerCase()) ||
        (module.description && module.description.toLowerCase().includes(searchText.toLowerCase())),
    )

    for (const module of matchedModules) {
      const project = projects.find((p) => p.id === module.projectId)
      if (project) {
        const department = departments.find((d) => d.id === project.departmentId)
        results.push({
          type: "module",
          id: module.id,
          projectId: module.projectId,
          name: module.name,
          projectName: project.name,
          department: department?.name || "",
          departmentId: project.departmentId,
          highlight: highlightText(module.name, searchText),
          description: module.description || "",
        })
      }
    }

    return results
  }, [searchText, projects, modules, departments])

  // Filter projects based on search and filters
  const filteredProjects = useMemo(() => {
    return projects.filter((project) => {
      const matchesSearch =
        !searchText ||
        project.name.toLowerCase().includes(searchText.toLowerCase()) ||
        (project.description && project.description.toLowerCase().includes(searchText.toLowerCase()))
      const matchesDepartment = !selectedDepartment || project.departmentId === selectedDepartment

      return matchesSearch && matchesDepartment
    })
  }, [projects, searchText, selectedDepartment])

  // Pagination
  const paginatedProjects = useMemo(() => {
    return filteredProjects.slice((currentPage - 1) * pageSize, currentPage * pageSize)
  }, [filteredProjects, currentPage, pageSize])

  // Get modules for a project
  const getProjectModules = (projectId: string) => {
    return modules.filter((m) => m.projectId === projectId)
  }

  const handleAddProject = () => {
    form.resetFields()
    setIsModalVisible(true)
  }

  const handleEditProject = (project: any) => {
    setEditingProject(project)
    editForm.setFieldsValue({
      name: project.name,
      departmentId: project.departmentId,
      description: project.description,
    })
    setIsEditModalVisible(true)
  }

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields()
      addProject({
        name: values.name,
        departmentId: values.departmentId,
        environment: "测试", // Default to test environment
        description: values.description,
      })
      setIsModalVisible(false)
      form.resetFields()
    } catch (error) {
      console.error("Validation failed:", error)
    }
  }

  const handleEditModalOk = async () => {
    try {
      const values = await editForm.validateFields()
      updateProject(editingProject.id, {
        name: values.name,
        departmentId: values.departmentId,
        description: values.description,
      })
      setIsEditModalVisible(false)
      setEditingProject(null)
    } catch (error) {
      console.error("Validation failed:", error)
    }
  }

  const handleModalCancel = () => {
    setIsModalVisible(false)
    form.resetFields()
  }

  const handleEditModalCancel = () => {
    setIsEditModalVisible(false)
    setEditingProject(null)
  }

  const handleDeleteProject = (id: string, name: string) => {
    confirm({
      title: "确定要删除此项目吗?",
      icon: <ExclamationCircleOutlined />,
      content: `删除项目 "${name}" 将同时删除其下所有模块和 Hosts 配置，此操作不可恢复。`,
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        deleteProject(id)
      },
    })
  }

  const handlePageChange = (page: number, size?: number) => {
    setCurrentPage(page)
    if (size) {
      setPageSize(size)
    }
  }

  const handleReset = () => {
    setSearchText("")
    setSelectedDepartment(undefined)
    setCurrentPage(1)
    setShowSearchResults(false)
  }

  const handleSearch = (value: string) => {
    setSearchText(value)
    setShowSearchResults(value.length > 0)
  }

  // Generate a consistent color based on department
  const getDepartmentColor = (departmentId: string) => {
    const department = departments.find((d) => d.id === departmentId)
    return department?.color || "#3b82f6"
  }

  // Format date to a more readable format
  const formatDate = (dateString: string) => {
    if (!dateString) return "-"
    const date = new Date(dateString)
    return date.toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    })
  }

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
      </div>
    )
  }

  return (
    <div className="container">
      <div className="projects-header mb-6">
        <div>
          <Title level={4} className="m-0">
            项目管理
          </Title>
          <Text type="secondary" className="text-sm">
            管理所有项目及其模块配置
          </Text>
        </div>
        <Space size={12}>
          <Button
            icon={<AppstoreOutlined />}
            type={viewMode === "card" ? "primary" : "default"}
            onClick={() => setViewMode("card")}
          >
            卡片视图
          </Button>
          <Button
            icon={<TableOutlined />}
            type={viewMode === "table" ? "primary" : "default"}
            onClick={() => setViewMode("table")}
          >
            表格视图
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAddProject}>
            创建项目
          </Button>
        </Space>
      </div>

      <div className="filter-card mb-6">
        <div className="filter-controls">
          <Input
            placeholder="搜索项目或模块..."
            prefix={<SearchOutlined className="search-icon" />}
            value={searchText}
            onChange={(e) => handleSearch(e.target.value)}
            allowClear
            className="filter-input"
          />

          <Select
            placeholder="选择部门"
            allowClear
            value={selectedDepartment}
            onChange={(value) => {
              setSelectedDepartment(value)
              setCurrentPage(1)
            }}
            className="filter-select"
          >
            {departments.map((dept) => (
              <Option key={dept.id} value={dept.id}>
                {dept.name}
              </Option>
            ))}
          </Select>

          <Button icon={<FilterOutlined />} onClick={handleReset} className="filter-button">
            重置
          </Button>
        </div>
      </div>

      {/* Search Results */}
      {showSearchResults && searchResults.length > 0 && (
        <Card className="enhanced-card mb-6">
          <Title level={5}>搜索结果</Title>
          <List
            itemLayout="horizontal"
            dataSource={searchResults}
            renderItem={(item) => (
              <List.Item
                actions={[
                  <Button
                    key="view"
                    type="link"
                    onClick={() => {
                      if (item.type === "project") {
                        navigate(`/projects/${item.id}`)
                      } else {
                        navigate(`/projects/${item.projectId}/modules/${item.id}`)
                      }
                      setShowSearchResults(false)
                    }}
                  >
                    查看
                  </Button>,
                ]}
              >
                <List.Item.Meta
                  avatar={
                    <div
                      className={`circle-icon-enhanced`}
                      style={{
                        width: "36px",
                        height: "36px",
                        fontSize: "16px",
                        background: `linear-gradient(135deg, ${getDepartmentColor(item.departmentId)} 0%, ${getDepartmentColor(item.departmentId)}80 100%)`,
                      }}
                    >
                      {item.type === "project" ? "P" : "M"}
                    </div>
                  }
                  title={
                    <Space>
                      {item.type === "module" && (
                        <>
                          <Text>{item.projectName} &gt; </Text>
                          <Text strong>{item.highlight}</Text>
                        </>
                      )}
                      {item.type === "project" && <Text strong>{item.highlight}</Text>}
                      <Tag
                        className="status-badge"
                        style={{
                          background: `${getDepartmentColor(item.departmentId)}20`,
                          color: getDepartmentColor(item.departmentId),
                          borderRadius: "12px",
                          border: "none",
                        }}
                      >
                        <TeamOutlined className="tag-icon" /> {item.department}
                      </Tag>
                    </Space>
                  }
                  description={item.description}
                />
              </List.Item>
            )}
          />
        </Card>
      )}

      {/* No search results message */}
      {showSearchResults && searchResults.length === 0 && (
        <Card className="enhanced-card mb-6">
          <Empty description={`没有找到与 "${searchText}" 相关的项目或模块`} />
        </Card>
      )}

      <div className="projects-content mb-6">
        {filteredProjects.length === 0 && !showSearchResults ? (
          <div className="empty-container">
            <Empty
              description={
                <span>
                  暂无项目
                  <br />
                  <Button type="primary" icon={<PlusOutlined />} onClick={handleAddProject} style={{ marginTop: 16 }}>
                    创建项目
                  </Button>
                </span>
              }
            />
          </div>
        ) : (
          !showSearchResults && (
            <>
              {viewMode === "card" ? (
                <Row gutter={[24, 24]}>
                  {paginatedProjects.map((project) => {
                    const department = departments.find((d) => d.id === project.departmentId)
                    const projectModules = getProjectModules(project.id)
                    const moduleCount = projectModules.length
                    const departmentColor = getDepartmentColor(project.departmentId)

                    return (
                      <Col xs={24} sm={12} md={8} lg={6} key={project.id}>
                        <Card
                          className="project-card-enhanced"
                          onClick={() => navigate(`/projects/${project.id}`)}
                          bordered={false}
                          style={{
                            height: "100%",
                            borderRadius: "12px",
                            overflow: "hidden",
                            boxShadow: "0 1px 2px rgba(0, 0, 0, 0.03)",
                            transition: "all 0.3s ease",
                            cursor: "pointer",
                            border: "1px solid #f1f5f9",
                          }}
                          bodyStyle={{ padding: "20px", height: "100%", display: "flex", flexDirection: "column" }}
                        >
                          <div style={{ display: "flex", alignItems: "center", gap: "16px", marginBottom: "16px" }}>
                            <div
                              className="circle-icon-enhanced"
                              style={{
                                width: "48px",
                                height: "48px",
                                fontSize: "20px",
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "center",
                                borderRadius: "50%",
                                color: "white",
                                flexShrink: 0,
                                background: `linear-gradient(135deg, ${departmentColor} 0%, ${departmentColor}80 100%)`,
                              }}
                            >
                              {project.name.charAt(0).toUpperCase()}
                            </div>
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div
                                style={{
                                  fontSize: "16px",
                                  fontWeight: 600,
                                  marginBottom: "4px",
                                  color: "#111827",
                                  whiteSpace: "nowrap",
                                  overflow: "hidden",
                                  textOverflow: "ellipsis",
                                }}
                              >
                                {project.name}
                              </div>
                              {department && (
                                <Tag
                                  style={{
                                    background: `${departmentColor}20`,
                                    color: departmentColor,
                                    borderRadius: "12px",
                                    border: "none",
                                  }}
                                >
                                  <TeamOutlined style={{ marginRight: "4px" }} /> {department.name}
                                </Tag>
                              )}
                            </div>
                          </div>

                          {project.description && (
                            <div
                              style={{
                                fontSize: "14px",
                                color: "#4b5563",
                                marginBottom: "16px",
                                display: "-webkit-box",
                                WebkitLineClamp: 2,
                                WebkitBoxOrient: "vertical",
                                overflow: "hidden",
                                flex: 1,
                              }}
                            >
                              {project.description}
                            </div>
                          )}

                          <Divider style={{ margin: "12px 0" }} />

                          <div
                            style={{
                              display: "flex",
                              justifyContent: "space-between",
                              alignItems: "center",
                              marginTop: "auto",
                            }}
                          >
                            <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
                              <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                                <AppstoreAddOutlined style={{ color: "#6366f1", fontSize: "16px" }} />
                                <span style={{ color: "#4b5563", fontSize: "13px" }}>{moduleCount} 个模块</span>
                              </div>
                              <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                                <ClockCircleOutlined style={{ color: "#8b5cf6", fontSize: "16px" }} />
                                <span style={{ color: "#4b5563", fontSize: "13px" }}>
                                  {formatDate(project.createdAt)}
                                </span>
                              </div>
                            </div>
                          </div>

                          <div
                            style={{
                              display: "flex",
                              justifyContent: "flex-end",
                              marginTop: "12px",
                            }}
                            onClick={(e) => e.stopPropagation()}
                          >
                            <Space>
                              <Tooltip title="编辑项目">
                                <Button
                                  type="text"
                                  size="small"
                                  icon={<EditOutlined />}
                                  onClick={(e) => {
                                    e.stopPropagation()
                                    handleEditProject(project)
                                  }}
                                />
                              </Tooltip>
                              <Tooltip title="删除项目">
                                <Button
                                  type="text"
                                  danger
                                  size="small"
                                  icon={<DeleteOutlined />}
                                  onClick={(e) => {
                                    e.stopPropagation()
                                    handleDeleteProject(project.id, project.name)
                                  }}
                                />
                              </Tooltip>
                            </Space>
                          </div>
                        </Card>
                      </Col>
                    )
                  })}
                </Row>
              ) : (
                <div className="enhanced-table">
                  <Table
                    dataSource={paginatedProjects}
                    rowKey="id"
                    pagination={false}
                    onRow={(record) => ({
                      onClick: () => navigate(`/projects/${record.id}`),
                      style: { cursor: "pointer" },
                    })}
                    columns={[
                      {
                        title: "项目名称",
                        dataIndex: "name",
                        key: "name",
                        render: (text, record) => {
                          const departmentColor = getDepartmentColor(record.departmentId)
                          return (
                            <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
                              <div
                                className="circle-icon-enhanced"
                                style={{
                                  width: "36px",
                                  height: "36px",
                                  fontSize: "16px",
                                  background: `linear-gradient(135deg, ${departmentColor} 0%, ${departmentColor}80 100%)`,
                                }}
                              >
                                {record.name.charAt(0).toUpperCase()}
                              </div>
                              <span style={{ fontWeight: 500 }}>{text}</span>
                            </div>
                          )
                        },
                      },
                      {
                        title: "部门",
                        dataIndex: "departmentId",
                        key: "departmentId",
                        render: (departmentId) => {
                          const department = departments.find((d) => d.id === departmentId)
                          const departmentColor = getDepartmentColor(departmentId)

                          return department ? (
                            <Tag
                              style={{
                                background: `${departmentColor}20`,
                                color: departmentColor,
                                borderRadius: "12px",
                                border: "none",
                              }}
                            >
                              <TeamOutlined style={{ marginRight: "4px" }} /> {department.name}
                            </Tag>
                          ) : (
                            "-"
                          )
                        },
                      },
                      {
                        title: "模块数",
                        key: "moduleCount",
                        render: (_, record) => {
                          const count = getProjectModules(record.id).length
                          return (
                            <Tag
                              style={{
                                background: "#f3e8ff",
                                color: "#7e22ce",
                                borderRadius: "12px",
                                border: "none",
                              }}
                            >
                              <AppstoreAddOutlined style={{ marginRight: "4px" }} /> {count}
                            </Tag>
                          )
                        },
                      },
                      {
                        title: "描述",
                        dataIndex: "description",
                        key: "description",
                        ellipsis: true,
                        render: (text) => text || "-",
                      },
                      {
                        title: "创建时间",
                        dataIndex: "createdAt",
                        key: "createdAt",
                        render: (date) => (
                          <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                            <ClockCircleOutlined style={{ color: "#8b5cf6" }} />
                            <span>{formatDate(date)}</span>
                          </div>
                        ),
                      },
                      {
                        title: "操作",
                        key: "action",
                        width: 120,
                        render: (_, record) => (
                          <Space size="small">
                            <Button
                              type="text"
                              size="small"
                              icon={<EditOutlined />}
                              onClick={(e) => {
                                e.stopPropagation()
                                handleEditProject(record)
                              }}
                            />
                            <Button
                              type="text"
                              danger
                              size="small"
                              icon={<DeleteOutlined />}
                              onClick={(e) => {
                                e.stopPropagation()
                                handleDeleteProject(record.id, record.name)
                              }}
                            />
                          </Space>
                        ),
                      },
                    ]}
                  />
                </div>
              )}

              {filteredProjects.length > pageSize && (
                <div className="pagination-container" style={{ marginTop: "24px", textAlign: "right" }}>
                  <Pagination
                    current={currentPage}
                    pageSize={pageSize}
                    total={filteredProjects.length}
                    onChange={handlePageChange}
                    showSizeChanger
                    pageSizeOptions={["8", "12", "24", "48"]}
                    showTotal={(total) => `共 ${total} 个项目`}
                    style={{ marginTop: "24px" }}
                  />
                </div>
              )}
            </>
          )
        )}
      </div>

      {/* Add Project Modal */}
      <Modal
        title="创建项目"
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={480}
        okText="创建"
        cancelText="取消"
      >
        <Form form={form} layout="vertical" style={{ marginTop: "16px" }}>
          <Form.Item name="name" label="项目名称" rules={[{ required: true, message: "请输入项目名称" }]}>
            <Input placeholder="请输入项目名称" />
          </Form.Item>
          <Form.Item name="departmentId" label="所属部门" rules={[{ required: true, message: "请选择所属部门" }]}>
            <Select placeholder="请选择部门">
              {departments.map((dept) => (
                <Option key={dept.id} value={dept.id}>
                  {dept.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="description" label="项目描述">
            <Input.TextArea rows={3} placeholder="请输入项目描述" />
          </Form.Item>
        </Form>
      </Modal>

      {/* Edit Project Modal */}
      <Modal
        title="编辑项目"
        open={isEditModalVisible}
        onOk={handleEditModalOk}
        onCancel={handleEditModalCancel}
        width={480}
        okText="更新"
        cancelText="取消"
      >
        <Form form={editForm} layout="vertical" style={{ marginTop: "16px" }}>
          <Form.Item name="name" label="项目名称" rules={[{ required: true, message: "请输入项目名称" }]}>
            <Input placeholder="请输入项目名称" />
          </Form.Item>
          <Form.Item name="departmentId" label="所属部门" rules={[{ required: true, message: "请选择所属部门" }]}>
            <Select placeholder="请选择部门">
              {departments.map((dept) => (
                <Option key={dept.id} value={dept.id}>
                  {dept.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="description" label="项目描述">
            <Input.TextArea rows={3} placeholder="请输入项目描述" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default ProjectsView
